package com.happy3w.ssp.schoolmatehome.service.user;

import com.happy3w.ssp.schoolmatehome.entity.User;
import com.happy3w.toolkits.utils.NameSqlBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.function.LongFunction;

@RequiredArgsConstructor
@Component
public class UserSearcher {
    private final NamedParameterJdbcTemplate jdbcTemplate;

    private List<UserSummary> findAllNotes(User curUser, LongFunction<NameSqlBuilder> buildSql) {
        long curUserId = curUser == null ? 0L : curUser.getId();
        NameSqlBuilder sqlBuilder = buildSql.apply(curUserId);
        return querySummary(sqlBuilder);
    }

    private List<UserSummary> querySummary(NameSqlBuilder sqlBuilder) {
        return jdbcTemplate.query(sqlBuilder.getSql(),
                sqlBuilder.getParams(),
                BeanPropertyRowMapper.newInstance(UserSummary.class));
    }

    public List<UserSummary> findIdols(User curUser, String query, int page, int size) {
        return findAllNotes(curUser, curUserId -> {
            return new NameSqlBuilder()
                    .append("""
                            select u.id,u.name,u.avatar,true as isFollowed,fs.created_at as date from follow_state fs
                            left join user u on u.id=fs.user_id
                            where fs.fans_id = :userId""", curUserId)
                    .appendIfValid("and u.name like :query", query,
                            StringUtils::hasText,
                            t -> "%" + t + "%")
                    .append("order by fs.created_at desc")
                    .appendPage(page, size);
        });
    }

    public List<UserSummary> findFans(User curUser, String query, int page, int size) {
        return findAllNotes(curUser, curUserId -> new NameSqlBuilder()
                .append("""
                        select u.id,u.name,u.avatar,fs2.id is not null as isFollowed,fs.created_at as date from follow_state fs
                        left join user u on u.id=fs.fans_id
                        left join follow_state fs2 on fs2.user_id =fs.fans_id and fs2.fans_id =fs.user_id
                        where fs.user_id = :userId""", curUserId)
                .appendIfValid("and u.name like :query", query,
                        StringUtils::hasText,
                        t -> "%" + t + "%")
                .append("order by fs.created_at desc")
                .appendPage(page, size));
    }
}
